
package jpoco.android;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;

import java.util.*;

import jpoco.client.*;

public class MainActivity extends AbstractActivity 
{
	private Client client;
    private SharedPreferences prefs;
    

	static
	{
		System.getProperties().put("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
		System.getProperties().put("org.apache.commons.logging.simplelog.defaultlog", "trace");
	}
	
    public MainActivity()
    {
    	super();
    }
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        prefs = getSharedPreferences("default", MODE_PRIVATE);

        client = null;
        
        

        ProviderListView providersView = new ProviderListView(this);
        providersView.setProviders(AndroidApplication.getAllProviders());
        providersView.setVisibility(View.GONE);
		providersView.setOnItemClickListener(new AdapterView.OnItemClickListener()
		{

			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				final ProviderView pview = (ProviderView) view;
				ClientSettings cs = AndroidApplication.getClientSettings(pview.getProviderName());
				
				final AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
				alert.setMessage("To get started, you will need to login to " + cs.getProviderName());
				
				alert.setButton("Login", new DialogInterface.OnClickListener()
				{

					public void onClick(DialogInterface dialog, int whichButton)
					{
						try
						{
							alert.dismiss();
							
							client = AndroidApplication.getClient(pview.getProviderName());
							
							final String url = client.getUserAuthorizationUrl();
	
							Log.i(this.getClass().getName(), url);
			    			
				        	persistRequestToken(pview.getProviderName());
			    				
							openWebBrowser(url);
						}
						catch (Throwable t)
						{
							onFail(t);
						}
						
					}
				});
				alert.show();
				
	        	
			}
			
		});
        		
        

        Uri uri = this.getIntent().getData();
        
        if (Util.isCallback(uri))
        {
        	Log.d("jpoco", "callback uri: " + uri.toString());
        	String providerName = Util.getProviderName(uri);
        	
        	Log.d("jpoco", "getProviderName(uri) = " + providerName);
        	
        	AndroidApplication.setCurrentProvider(providerName);
        	
        	client = AndroidApplication.getClient(providerName);
        	client.setRequestToken(loadRequestToken(providerName));
        	fetchAccessToken(Util.getToken(uri));
        	
        	Intent i = new Intent();
        	i.setClass(this, ContactsActivity.class);
        	startActivity(i);
        }
        
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
       
        layout.addView(providersView);
        
        providersView.setVisibility(View.VISIBLE);
        
        
        setContentView(layout);
    }

    protected void fetchAccessToken(String requestToken)
    {
    	
        client.fetchAccessToken();
				
    	persistUserAccessToken(client.getClientSettings().getProviderName());
				
    }
    
    protected void persistUserAccessToken(String prefix)
    {
        SharedPreferences.Editor editor = prefs.edit();
        
          editor.putString(prefix + ".user.public", client.getClientSettings().getUserSpecificAccessToken().getPublicToken());
  //        editor.putString("user.public", "");
          editor.putString(prefix + ".user.secret", client.getClientSettings().getUserSpecificAccessToken().getSecret());
        
        editor.commit();
    }

    protected Token loadRequestToken(String prefix)
    {
        SharedPreferences.Editor editor = prefs.edit();
        
        Token t = new Token();
        t.setPublicToken(prefs.getString(prefix + ".request.public", ""));
        t.setSecret(prefs.getString(prefix + ".request.secret", ""));
        
        return t;
    }

    protected Token loadUserSpecificAccessToken(String prefix)
    {
        SharedPreferences.Editor editor = prefs.edit();
        
        Token t = new Token();
        t.setPublicToken(prefs.getString(prefix + ".user.public", ""));
        t.setSecret(prefs.getString(prefix + ".user.secret", ""));
        
        return t;
    }
    
    protected void persistRequestToken(String prefix)
    {
        SharedPreferences.Editor editor = prefs.edit();
        
        editor.putString(prefix + ".request.public", client.getRequestToken().getPublicToken());
        editor.putString(prefix + ".request.secret", client.getRequestToken().getSecret());
        
        editor.commit();
    }

    protected void onDestroy()
    {
    	super.onDestroy();

    }

}


